package abel.wlmr.model.unit;

import org.joda.time.DateTime;

import abel.wlmr.model.WlmrBaseUnit;
import abel.wlmr.model.WlmrException;
import abel.wlmr.model.type.C1DateTimeType;
import io.netty.buffer.ByteBuf;

/**
 * 数据单元标识（DA=0）
 * F1 登录 p0
 * F2 退出登录 p0
 * F3 心跳 p0
 * 
 * 终端时钟 见附录 C.1 6
 * 
 * @author Abel
 *
 */
public class Afn02F3Unit extends WlmrBaseUnit {
    private static final short FIXED_LENGTH = 6;

    /**
     * 终端时钟 见附录 C.1 6
     */
    private C1DateTimeType termClock;

    public Afn02F3Unit() {
        this((short) -1);
    }

    public Afn02F3Unit(short len) {
        super(len);

        termClock = new C1DateTimeType(DateTime.now(), true);
    }

    /* (non-Javadoc)
     * @see abel.wlmr.model.AppUnitPart#appendBuf(io.netty.buffer.ByteBuf)
     */
    @Override
    public ByteBuf appendBuf(ByteBuf buf) {
        if (termClock == null) {
            throw new IllegalArgumentException("meter clock should be 6 bytes long");
        }

        // may throw IAE
        termClock.appendBuf(buf);

        return buf;
    }

    /* (non-Javadoc)
     * @see abel.wlmr.model.AppUnitPart#parseBuf(io.netty.buffer.ByteBuf)
     */
    @Override
    public int parseBuf(ByteBuf buf) throws WlmrException {
        if (checkBuffer(buf) < 0) {
            return -1;
        }

        termClock = new C1DateTimeType((short) 6);
        termClock.parseBuf(buf);

        return FIXED_LENGTH;
    }

    /* (non-Javadoc)
     * @see abel.wlmr.model.WlmrDataPart#getFinalLen()
     */
    @Override
    public short getFinalLen() {
        return FIXED_LENGTH;
    }

    /* (non-Javadoc)
     * @see abel.wlmr.model.WlmrDataPart#getMinLength()
     */
    @Override
    public int getMinLength() {
        return FIXED_LENGTH;
    }

    /* (non-Javadoc)
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        return String.format("{termClock:%s}", termClock);
    }

    /**
     * 终端时钟 见附录 C.1 6
     * 
     * @return
     */
    public DateTime getTermClockJoda() {
        if (termClock == null) {
            throw new IllegalArgumentException("termal clock can't be null");
        }

        return termClock.getDtValue();
    }

    /**
     * 终端时钟 见附录 C.1 6
     * 
     * @return the termClock
     */
    public C1DateTimeType getTermClock() {
        return termClock;
    }

    /**
     * 终端时钟 见附录 C.1 6
     * 
     * @param termClock
     *            the termClock to set
     */
    public void setTermClock(C1DateTimeType termClock) {
        if (termClock == null || termClock.getDtValue() == null) {
            throw new IllegalArgumentException("termal clock can't be null");
        }

        this.termClock = termClock;
    }

}
